package at.horario.web.pages.data;

import at.horario.model.GenericObject;
import at.horario.service.GenericManager;
import at.horario.web.property.editor.GenericModel;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

public class GenericSortableDataProvider<T extends GenericObject, PK extends Serializable> extends SortableDataProvider {
    private GenericManager<T, PK> genericManager;
    private T object;

    public GenericSortableDataProvider(GenericManager<T, PK> genericManager) {
        this.genericManager = genericManager;
    }

    public GenericSortableDataProvider(GenericManager<T, PK> genericManager, T object) {
        this.genericManager = genericManager;
        this.object = object;
    }

    public GenericSortableDataProvider() {
        // default sort
        setSort("id", true);
    }

    public Iterator<T> iterator(int first, int count) {
        DetachedCriteria criteria = genericManager.buildCriteria(object);
        SortParam sp = getSort();
        if (sp != null) {
            if (sp.isAscending()) {
                criteria.addOrder(Order.asc(sp.getProperty()));
            } else {
                criteria.addOrder(Order.desc(sp.getProperty()));
            }
        }
        List<T> list = genericManager.getAll(criteria, first, count);
        return list.iterator();
    }


    public IModel model(Object object) {
        return new GenericModel((T) object, genericManager);
    }

    public int size() {
        return genericManager.getAll().size();
    }
}